package com.yonyou.eco.taxclouddemo.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * description:
 *
 * @Author: wangweir
 * @Date: 2020/10/29 13:51
 */
@Slf4j
public class SignUtils {

  public static String sign(String appsecret, Map<String, String> params) {
    List<String> keys = new ArrayList<>(params.keySet());
    Collections.sort(keys);
    String toSign = keys.stream().map(data -> data + "=" + params.get(data))
        .collect(Collectors.joining("&"));
    toSign = toSign + "#" + appsecret;
    log.debug("toSign:{}", toSign);
    String sha256hex =null;
    try {
      MessageDigest crypt = MessageDigest.getInstance("SHA-256");
      crypt.reset();
      crypt.update(toSign.getBytes("UTF-8"));
      sha256hex = byteToHex(crypt.digest());
      log.debug("加签sha256hex:{}", sha256hex);
    } catch (Exception e) {
      log.error(e.getMessage());
    }
    return sha256hex;
  }

  private static String byteToHex(byte[] hash) {
    Formatter formatter = new Formatter();
    for (byte b : hash) {
      formatter.format("%02x", b);
    }
    String result = formatter.toString();
    formatter.close();
    return result;

  }

  public static void main(String[] args) throws UnsupportedEncodingException {
     //注意，签名字符串的顺序工具类已按照key值进行排序，无须再关注顺序
     /**
     * 接口一签名
     */
      /*LinkedHashMap<String, String> data = new LinkedHashMap<>();
      data.put("appid","wwcc20133b721a60ea");
      data.put("code","9ijA5DxnIFTQFOVUE2eU_BrAyW1dw7lFcgB9_Fu4XBY");
      data.put("ts","1653898092119");
      data.put("tag","taxCloud");//签名时必须带上
      String sing = sign("pwd",data);
      System.out.println(sing.equals("0083af1a2c3235c530a4c3efa2fd10bd8d960a26c03b702e5d27c2c4ee3ec178"));*/
      /**
       * 接口二签名
       */
      /*LinkedHashMap<String, String> data = new LinkedHashMap<>();
      data.put("appid","wwcc20133b721a60ea");
      data.put("pageUrl","https%3A%2F%2Fyesfp.yonyoucloud.com%2Fmobileinvoice%2Fweapp%2Findex.html%3Fh5vendor%3Dkw_test%26state%3Dinvoice-list%26code%3DVgJTDz2mw_uJgCSrQIgBzfDU6kuuHO_32KLk8K7W4Ho%26state%3D");
      data.put("ts","1653898707202");
      data.put("tag","taxCloud");//签名时必须带上
      String sing = sign("pwd",data);
      System.out.println(sing.equals("4014147743952dc9534f2004d1f0b4bf37a4b130eecf7411c4fb6b976720d759"));
*/
       System.out.println(URLEncoder.encode("http://47x826661y.qicp.vip/auth", "UTF-8"));
  }

}
